#!/bin/bash

# wget -O /tmp/pui.sh https://gitee.com/gemilk/image_repo/raw/master/pull-images.sh && chmod +x /tmp/pui.sh && /tmp/pui.sh num && rm -f /tmp/pui.sh

# 登录到 Docker 镜像仓库（可注释掉，若已登录）
if [ -f "/root/.docker/config.json" ]; then
  echo "login alrealy"
else
  docker login --username=448267696@qq.com crpi-9qpzy3u9htsic0vd.cn-shanghai.personal.cr.aliyuncs.com
fi

declare -A images=(
  [100]="tailscale-tailscale:stable"
  [101]="tailscale-tailscale:stable-arm64"
  
  [110]="headscale-headscale:stable"
  [111]="ghcr.io-gurucomputing-headscale-ui:latest"

  [120]="shadowofgost-derper:main"
  [121]="shadowofgost-derper:ip"

  [200]="linuxserver-nginx:latest"
  [201]="filebrowser-filebrowser:v2-s6"
  [202]="portainer-portainer-ce:latest"
  [203]="btpanel-baota:latest-arm64"


  [210]="snowdreamtech-frps:latest"
  [211]="snowdreamtech-frpc:latest-arm64"


  [500]="linuxserver-calibre-web:latest"
  [666]="ttfund:main-arm64"
  [777]="openwrt:latest"
  
)

# 阿里云镜像仓库前缀
aliyun="crpi-9qpzy3u9htsic0vd.cn-shanghai.personal.cr.aliyuncs.com/homesmart"

# 拉取镜像并重新打标签的函数
pull_and_retag() {
  local short_name="$1"
  local image_name="${aliyun}/${short_name}"

  echo "拉取镜像: $image_name"
  docker pull "$image_name"

  # 获取镜像 ID
  image_id=$(docker images --format "{{.ID}}" --filter "reference=${image_name}")

  # remove -arm64
  short_name=$(echo "$short_name" | sed -E 's/-arm64$//')

  if [[ $short_name == ghcr.io-* ]]; then
    # 将前两个 - 替换为 /
    new_tag=$(echo "$short_name" | sed -E 's/-/\//; s/-/\//')
  else
    # 将第一个 - 替换为 /
    new_tag=$(echo "$short_name" | sed -E 's/-/\//')
  fi

  echo "打标签: $image_id -> $new_tag"
  docker tag "$image_id" "$new_tag"

  echo "镜像标签已更新为: $new_tag"

  # 删除原始镜像标签（不删除镜像本体）
  docker rmi "$image_name"
  echo "已删除原始镜像标签: $image_name"
}

# 如果没有参数，提示用法
if [ "$#" -eq 0 ]; then
  echo "用法: $0 [编号...]"
  echo "可用镜像列表："
  for i in "${!images[@]}"; do
    echo "  $i) ${images[$i]}"
  done
  exit 1
fi

# 处理传入的每个编号
for index in "$@"; do
  if [[ -n "${images[$index]}" ]]; then
    pull_and_retag "${images[$index]}"
  else
    echo "❌ 无效编号: $index"
  fi
done
